<?php

namespace App\Service;
use Hyperf\DbConnection\Db;
use Hyperf\Utils\ApplicationContext;
use GuzzleHttp\Client;
class DyService
{
    public function __construct()
    {
        $container = ApplicationContext::getContainer();
        $this->redis = $container->get(\Hyperf\Redis\Redis::class);
        $this->httpclient = new Client();
    }

    public function get_applet_id($order_id)
    {
        $res = Db::table('data_payment')->select('applet_id')->where('order_id', $order_id)->first();
        return $res;
    }

    public function get_applet(string $applet_id)
    {
        # 获取小程序基本配置
        $redis_key = "applet:config";
        $applet_info = $this->redis->hGet($redis_key, $applet_id);
        $applet_info = json_decode($applet_info, true);
        if (empty($applet_info)) {
            # 获取小程序基本信息
            $applet_info = Db::table("applet")->where([
                "id" => $applet_id
            ])->first();
            $applet_info = $this->object_to_find_array($applet_info);
            $this->redis->hSet($redis_key, $applet_id, json_encode($applet_info));
        }
        return $applet_info;
    }

    public function syn_order($applet_id,$open_id,$order_id,$amount,$status=0)
    {
        $stat =[
            0=>'待支付',
            1=>'已支付',
            2=>'已取消',
            5=>'退款中',
            6=>'已退款',
            8=>'退款失败',
        ];
        $applet = $this->get_applet($applet_id);
        $dy_access_token = $this->get_dy_access_token($applet_id);
        $order_info  = Db::table("data_payment")->where(["order_id"=>$order_id])->first();
        if(empty($order_info)) {
            var_dump('找不到订单');
            return 404;
        }
        $url = "https://developer.toutiao.com/api/apps/order/v2/push";
        $item_list = [
            'item_code'=>'item_code',
//            'img'=>'https://ky-dj.oss-accelerate.aliyuncs.com/images/13/130bd7613ae963a58260632ea5e26827.jpg',
            'img'=>'https://ky-dj.oss-cn-shenzhen.aliyuncs.com/images/00/00hghhgggg45tryst.png',
            'title'=>'购买短剧',
            'amount'=>1,
            'price'=>intval($amount)
        ];
        $order_detail = array(
            'order_id'=>"$order_id",
            'create_time'=>strtotime($order_info->create_at)*1000,
            'status'=>$stat[$status],
            'amount'=>1,
            'total_price'=>intval($amount),
            'detail_url'=>'pages/tabBar/square/square',
            'item_list'=>[$item_list]
        );
        $order_detail = json_encode($order_detail);
        var_dump($order_detail);

        $post_data = [];
        $post_data['access_token'] = $dy_access_token;
//        $post_data['app_name'] = $applet['name'];
        $post_data['app_name'] = 'douyin';
        $post_data['open_id'] = $open_id;
        $post_data['order_status'] = $status;
        $post_data['order_detail'] = $order_detail;
        $post_data['order_type'] = 0;
        $post_data['update_time'] = time();
        $res = $this->curl_post($url,$post_data);
//        return json_decode($http, true);
    }
    public function get_dy_access_token(string $applet_id="20000"){
        $key = 'dy_access_token';
        $key .= $applet_id;
        $access_token = $this->redis->get($key);
        if(empty($access_token)){
            $dy_appid = '';
            $dy_secret = '';
            # 获取小程序基本信息
            $applet_info = Db::table("applet")->where([
                "id"=>$applet_id
            ])->first();

            if(!empty($applet_info)){
                $dy_appid = $applet_info->app_id;
                $dy_secret = $applet_info->app_secret;
            }
            $url = "https://developer.toutiao.com/api/apps/v2/token";
            $post_data =[];
            $post_data['appid'] =$dy_appid;
            $post_data['secret'] =$dy_secret;
            $post_data['grant_type'] ='client_credential';
            $access_token_info = $this->curl_post($url,$post_data);
            var_dump($access_token_info);
            if ($access_token_info["err_no"] == 0 ){
                $access_token = $access_token_info['data']["access_token"];
                $this->redis->set($key,$access_token);
                $this->redis->expire($key,7100);
            }else{
                $access_token = "";
            }
        }
        return $access_token;
    }
    public function ttsign($params, $SALT)
    {
        $rList = array();
        foreach ($params as $k => $v) {
            if ($k == "other_settle_params" || $k == "app_id" || $k == "sign" || $k == "thirdparty_id")
                continue;
            $value = trim(strval($v));
            $len = strlen($value);
            if ($len > 1 && substr($value, 0, 1) == "\"" && substr($value, $len, $len - 1) == "\"")
                $value = substr($value, 1, $len - 1);
            $value = trim($value);
            if ($value == "" || $value == "null")
                continue;
            array_push($rList, $value);
        }
        array_push($rList, 'BxSaFUBC5vyhTVZb3ySW6SO9g7a5M27aPCjqxVvR');
        sort($rList, 2);
        return md5(implode('&', $rList));
    }

    public function httpPost($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        if (!$data) return false;
        if (is_array($data)) {
            $data = json_encode($data);
        }
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
            'Content-Length:' . strlen($data),
            'Cache-Control: no-cache',
            'Pragma: no-cache'
        ));
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
    public function curl_post($url,$data){
        $headers = [
            'Content-Type' => 'application/json',
        ];
        $response = $this->httpclient->post($url, [
            'headers' => $headers,
            'json' => $data,
        ]);
        $content = $response->getBody()->getContents();
        var_dump($content);
        return json_decode($content,true);
    }
}